iT邦幫忙

2021 iThome 鐵人賽

DAY 1
0
自我挑戰組

網路前端自我挑戰系列 第 1

python證照必考題 得票數計算 選舉題目 投票問題TQC+ 程式語言 Python 3 _ 409

  • 分享至 

  • xImage
  •  

*TQC+ 程式語言 Python 3 _ 409 得票數計算 *
說明: 某次選舉有兩位候選人,分別是No.1: Nami、No.2: Chopper。
請撰寫一程式,輸入五張選票,輸入值如為1即表示針對1號候選人投票;
輸入值如為2即表示針對2號候選人投票,如輸入其他值則視為廢票。
每次投完後需印出目前每位候選人的得票數,最後印出最高票者為當選人;
如最終計算有相同的最高票數者或無法選出最高票者,顯示
【=> No one won the election.】。
-------------------------------
輸入與輸出會交雜如下,輸出的部份以粗體字表示(程式執行狀況擷圖)
2
Total votes of No.1: Nami = 0
Total votes of No.2: Chopper = 1
Total null votes = 0
1
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 1
Total null votes = 0
8
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 1
Total null votes = 1
2
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 2
Total null votes = 1
2
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 3
Total null votes = 1 => No.2 Chopper won the election.

python解題一: 考試上機作答沒問題,但現實狀況不符。

nami_vote = 0 
chopper_vote = 0
null_vote = 0

for i in range(5):   #for 回圈。五次投票
    vote = int(input())

    if vote == 1:
        nami_vote += 1
    elif vote == 2:
        chopper_vote += 1
    else:
        null_vote += 1

    print('Total votes of No.1: Nami = ', nami_vote)    
    print('Total votes of No.2: Chopper = ', chopper_vote)
    print('Total null votes = ', null_vote)

if nami_vote > chopper_vote:    
    print('=> No.1 Nami won the election.')
elif chopper_vote > nami_vote:
    print('=> No.2 Chopper won the election.')
else:
    print('=> No one won the election.')   
    
   #這種方法在廢票多於前兩位候選人會出現,bug 。錯判 某位候選人照樣勝出。
null 3
nami 2
chopper 1. 判定: nami勝出的謬誤
**解法二:**
nami,chop,null= 0,0,0

for i in range(5):
     vote = int(input())
     if vote == 1: nami +=1
     elif vote == 1: chop +=1
     elif: null +=1
     
     print("Total vote of No.1: Nami =",nami)
     print("Total vote of No.2: Chopper =",chop)
     print("Total nul votes =" ,null)

if null >= nami and null >=chop or nami == chop: #先界定各種廢票
       print("=> No one won the election.")
elif nami> chop: 
       print("=> No.1 Nami won the election.")
else:
       print("=> No.2 Chopper won the election.")
 **   解法三:**
    
nami,chop,null =0,0,0

for i in range(5):
         vote = input()
         if vote == "1":nami +=1
         elif vote =="2": chop +=1 #把 投票變成字串,確定頭1or2有效,其他寫錯的不會生效。
          elif: null += 1
     
     print("Total vote of No.1: Nami =",nami)
     print("Total vote of No.2: Chopper =",chop)
     print("Total nul votes =" ,null)

if null >= nami and null >=chop or nami == chop:
       print("=> No one won the election.")
elif nami> chop:
       print("=> No.1 Nami won the election.")
else:
       print("=> No.2 Chopper won the election.")

下一篇
python 奇偶數個數計算
系列文
網路前端自我挑戰4
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言